package cn.tianyigps.tianyigpsm7clean.kafka;

import cn.tianyigps.tianyigpsm7clean.handler.CleanHandler;
import cn.tianyigps.tianyigpspublic.bean.StandardModel;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static cn.tianyigps.tianyigpspublic.util.JavaTypeUtil.getCollectionType;


/**
 * @author cui.guibin
 * @date 2018/9/6
 * @version 1.0
 * Description: 消费standardModel数据
 */
@Component
@Slf4j
public class DataConsumer {

    @Autowired
    private CleanHandler cleanHandler;
    /**
     * kafka监听清洗数据
     * @param json
     */
    @KafkaListener(topics = {"m7_inbound"})
    public void receive(String json) {
        if (StringUtils.isEmpty(json)) {
            log.info("上报服务发送的json为:null");
            return;
        }
        System.out.println(json);
        List<StandardModel> standardModels = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JavaType javaType = getCollectionType(ArrayList.class, StandardModel.class);
            standardModels = objectMapper.readValue(json,javaType);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("json 解析失败: "+ json);
        }
        if (!Optional.ofNullable(standardModels).isPresent() || standardModels.isEmpty())
            return;

        cleanHandler.handlerEquipment(standardModels);
    }

}
